<template>
  <div class="content1">
    <div class="headerBox">
      <el-button type="primary" @click="addrole(0)">添加用户</el-button>
      <el-button type="danger" @click="delrole">移除用户</el-button>
    </div>
    <div class="searchBox">
      <el-form class="elForm" :model="PaginationObj">
        <el-form-item label="手机号：" label-width="80px">
          <el-input
            type="text"
            v-model="PaginationObj.phone"
            style="width:200px"
            placeholder="请输手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名：" label-width="80px">
          <el-input
            type="text"
            v-model="PaginationObj.name"
            style="width:200px"
            placeholder="请输姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属部门：" label-width="100px">
          <el-input
            type="text"
            v-model="PaginationObj.deptName"
            style="width:200px"
            placeholder="请输所属部门"
          ></el-input>
        </el-form-item>
        <el-form-item label-width="40px">
          <el-button type="primary" size="mini" @click="changePageNumHandle(1)"
            >查询</el-button
          >
 
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="tableLoading"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="手机号" prop="phone"> </el-table-column>
      <el-table-column label="姓名" prop="name"> </el-table-column>
      <el-table-column label="所属部门" prop="deptName"> </el-table-column>
      <el-table-column label="所属角色" prop="roleName"> </el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        :formatter="formatDate"
      >
      </el-table-column>
      <el-table-column
        label="修改时间"
        prop="updateTime"
        :formatter="formatDate"
      >
      </el-table-column>
      <el-table-column label="账号状态" prop="state" :formatter="formatType">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            @click="updateRoleHandle(scope.row)"
            type="text"
            size="small"
            >修改权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="paginationBox">
      <el-pagination
        style="margin:20px"
        background
        :total="totalSize"
        :current-page.sync="PaginationObj.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="changePageNumHandle"
        @size-change="changePageSizeHandle"
      />
    </div>

    <el-dialog
      width="60%"
      :visible.sync="centerDialogVisible"
      center
      @close="closeDialogHandle"
      @opened="openeDialogHandle"
    >
      <div>
        <h3>
          {{ changeRoleType === "add" ? "添加用户权限" : "修改用户权限" }}
        </h3>
        <div v-if="changeRoleType === 'add'" class="searchBox">
          <el-form :model="phonePaginationObj" ref="phoneRef" :inline="true">
            <el-form-item label="手机号：" label-width="70px" prop="phone">
              <el-input
                type="text"
                v-model.number="phonePaginationObj.phone"
                style="width:200px"
                placeholder="请输手机号"
              ></el-input>
            </el-form-item>
            <el-form-item label="姓名：" label-width="60px" prop="name">
              <el-input
                type="text"
                v-model="phonePaginationObj.name"
                style="width:200px"
                placeholder="请输姓名"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="所属部门："
              label-width="100px"
              prop="deptName"
            >
              <el-input
                type="text"
                v-model="phonePaginationObj.deptName"
                style="width:200px"
                placeholder="请输所属部门"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePhonePageNumHandle(0)"
                >查询</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-table
          v-if="changeRoleType === 'add'"
          :data="tableData2"
          style="width: 100%"
          @selection-change="handleSelectionChange2"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="手机号" prop="mobile"> </el-table-column>
          <el-table-column label="姓名" prop="name"> </el-table-column>
          <el-table-column label="所属部门" prop="department">
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="changeRoleType === 'add'"
          style="margin:20px"
          background
          :total="phonePaginationTotal"
          :current-page.sync="phonePaginationObj.pageNum"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="changePhonePageNumHandle"
          @size-change="changePhonePageSizeHandle"
        />
        <h3 style="margin:20px 0">所属角色</h3>
        <div class="roleBox">
          <div
            :class="currtentIndex == index ? 'active' : 'default'"
            @click="checkRole(index, item)"
            v-for="(item, index) in routerList"
            :key="index"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">{{
          changeRoleType === "add" ? "添加" : "修改"
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import Const from "@/api/Const.js";
import { formatDate } from "@/assets/js/data";
export default {
  name: "limitsItem",
  components: { Pagination },
  data() {
    return {
      tableLoading: false,
      roleName: "",
      updateCurrentObj: {},
      changeRoleType: "add",
      form2: {},
      params1: {},
      params2: {},
      tableData: [{ phone: "15110227276" }],
      tableData2: [],
      centerDialogVisible: false,
      totalSize: 0,
      totalSize1: 0,
      jsonData: {
        currentPage: 1,
        pageSize: 10,
        currentPage1: 1,
        pageSize1: 10
      },
      PaginationObj: {
        phone: "",
        name: "",
        deptName: "",
        pageSize: 10,
        pageNum: 1
      },
      phonePaginationObj: {
        phone: "",
        name: "",
        deptName: "",
        pageSize: 10,
        pageNum: 1
      },
      phonePaginationTotal: 0,
      checkList: [],
      checkList2: [],
      routerList: [],
      currtentIndex: 0
    };
  },
  created() {
    this.initData();
  },
  mounted() {},
  filters: {
    formatDate(time) {
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  methods: {
    changePhonePageNumHandle(pageNum) {
      this.phonePaginationObj.pageNum = pageNum;
      this.addrole();
    },
    changePhonePageSizeHandle(pageSize) {
      this.phonePaginationObj.pageSize = pageSize;
      this.addrole();
    },
    changePageNumHandle(pageNum) {
      this.PaginationObj.pageNum = pageNum;
      this.getSeach1();
    },
    changePageSizeHandle(pageSize) {
      this.PaginationObj.pageSize = pageSize;
      this.getSeach1();
    },
    formatType: function(row, column) {
      if (row.state === "0") {
        return "正常";
      }
      if (row.state === "1") {
        return "禁用";
      }
    },
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if (!data) {
        return "";
      }
      let dt = new Date(data);
      return (
        dt.getFullYear() +
        "-" +
        (dt.getMonth() + 1) +
        "-" +
        dt.getDate() +
        " " +
        dt.getHours() +
        ":" +
        dt.getMinutes() +
        ":" +
        dt.getSeconds()
      );
    },
    initData() {
      this.$axios
        .get(Const.api.selectUser, {
          params: this.phonePaginationObj
        })
        .then(res => {
          let { data } = res;
          if (data.code == 0) {
            this.tableData = data.data.list;
            this.totalSize = Number(data.data.total);
          }
        });
    },
    openeDialogHandle() {
      this.selectRoleListHandle();
    },
    // 关闭对话框
    closeDialogHandle() {
      if (this.changeRoleType === "add") {
        this.$refs.phoneRef.resetFields();
      }
      this.changeRoleType = "add";

      this.phonePaginationObj.pageNum = 1;
      this.phonePaginationObj.pageSize = 10;
      this.currtentIndex = 0;
      this.updateCurrentObj = {};
    },
    selectRoleListHandle() {
      var that = this;
      this.$axios.get(Const.api.selectRoleList).then(res => {
        let { data } = res;
        if (data.code == 0) {
          that.routerList = data.data;
          if (that.updateCurrentObj) {
            let index = that.routerList.findIndex(
              item => item.id === that.updateCurrentObj.roleId
            );
            if (index !== -1) {
              that.currtentIndex = index;
            } else {
              that.currtentIndex = 0;
            }
          }
        }
      });
    },

    saveUser() {
      var that = this;
      console.log(
        this.routerList[this.currtentIndex],
        "this.routerList[this.currtentIndex]"
      );

      let role_id = this.routerList[this.currtentIndex].id;
      let userIdArr;
      if (this.changeRoleType === "add") {
        if (that.checkList2.length === 0) {
          this.$message.error("请选择要添加的数据！");
          return false;
        }
        userIdArr = that.checkList2.map(item => item.userId).join();
      } else {
        userIdArr = this.updateCurrentObj.ddUserId;
      }

      that.$axios
        .get(Const.api.saveUser, {
          params: {
            roleId: role_id,
            userIds: userIdArr
          }
        })
        .then(res => {
          if (res.data.code == 0) {
            this.$axios.get(Const.api.saveOprateLog,{
                  params:{
                    model:'权限配置',
                    oprate: this.changeRoleType==="edit"?'修改':'新增'
                  }
                });
            this.initData();
            that.$message({
              message: "保存成功！",
              type: "success"
            });
          } else {
            this.$message(res.data.message);
          }
        });
      this.centerDialogVisible = false;
    },
    addrole() {
      // 新增权限
      this.$axios
        .get(Const.api.selectUser2, {
          params: this.phonePaginationObj
        })
        .then(res => {
          console.log(res);
          let { data } = res;
          if (data.code == 0) {
            this.tableData2 = data.data.list;
            this.phonePaginationTotal = Number(data.data.total);
          }
        });

      this.centerDialogVisible = true;
    },
    updateRoleHandle(row) {
      console.log(row, "wwwwww");
      this.updateCurrentObj = row;
      this.changeRoleType = "edit";
      this.centerDialogVisible = true;
      this.changeRole(row.roleId);
    },
    getSeach1(num) {
      var that = this;
      that.$axios
        .get(Const.api.selectUser, {
          params: this.PaginationObj
        })
        .then(res => {
          console.log(res);
          if (res.data.code == 0) {
            var data = res.data.data.list;
            that.tableData = data;
            that.jsonData.currentPage = res.data.data.pageNum;
            that.jsonData.pageSize = res.data.data.pages;
            that.totalSize = Number(res.data.data.total);
          }
        });
    },
    getSeach2(num) {},
    delrole() {
      if (this.checkList.length == 0) {
        this.$message({
          message: "请先选择要移除的账号！",
          type: "warning"
        });
      } else {
        let par = [];
        this.checkList.forEach(item => {
          par.push(item.id);
        });
        this.$axios
          .get(Const.api.deleteUser, {
            params: {
              ids: par.join(",")
            }
          })
          .then(res => {
            let { data } = res;
            if (data.code == 0) {
              this.initData();
              this.$message({
                message: "删除成功！",
                type: "success"
              });
            } else {
              this.$message.error(data.message);
            }
          });

        console.log(this.checkList);
      }
    },
    handleSelectionChange(val) {
      this.checkList = val;
    },
    handleSelectionChange2(val) {
      console.log(val, "val");
      this.checkList2 = val;
    },
    changeRole(role) {
      var that = this;
      this.routerList.forEach((item, index) => {
        if (role == item.key) {
          that.currtentIndex = index;
        }
      });
    },
    checkRole(index, item) {
      console.log(index, item, "index,item");
      this.currtentIndex = index;
    }
  }
};
</script>
<style lang="scss" scoped>
.content1 {
  background-color: #fff;
  margin-top: 20px;
  .headerBox {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }
  .searchBox {
    display: flex;
    flex-direction: row;
    margin: 10px 10px 0 10px;
    .elForm {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      //  justify-content: ;
    }
  }
  .roleBox {
    border: 1px solid #999;
    border-radius: 10px;
    padding: 15px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    .default {
      background-color: #fff;
      color: #333;
      border: 1px solid #999;
    }
    .active {
      background-color: #78acff;
      color: #fff;
      border: 1px solid #fff;
    }
    .default,
    .active {
      margin: 10px;
      width: 180px;
      height: 45px;
      font-weight: 600;
      display: flex;
      flex-direction: row;
      justify-content: center;
      flex-wrap: wrap;
      align-items: center;
      border-radius: 10px;
      margin-left: 20px;
      cursor: pointer;
    }
  }
}
.paginationBox {
  display: flex;
  justify-content: flex-end;
}
</style>
